package com.zz.framework.core.base

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.annotation.LayoutRes
import androidx.fragment.app.Fragment
import com.zz.framework.core.ext.toJson
import com.zz.framework.core.utils.IntentBuilder
import com.zz.framework.core.utils.LogUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

/**
 * Copyright © 2025 zhun All rights reserved.
 * Created by ZhaoZhun on 2025/2/18 13:45.
 * @author: ZhaoZhun 1820022519@qq.com
 * @version: V1.0
 */
abstract class BaseFragment(@LayoutRes contentLayoutId: Int) : Fragment(contentLayoutId) {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
//        requireActivity().enableEdgeToEdge()
//        ViewCompat.setOnApplyWindowInsetsListener(view) { v, insets ->
//            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
//            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
//            insets
//        }
        initView()
        initData()
        initObserver()
        EventBus.getDefault().register(this)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }
    @Subscribe
    open fun onMessage(e:Byte){
    }

    open fun initView() {}
    open fun initData() {}
    open fun initObserver() {}


    public fun getIntent(): Intent {
        return requireActivity().intent
    }

    fun getBaseActivity(): BaseActivity? {
        if (activity is BaseActivity) {
            return activity as BaseActivity
        } else {
            return null
        }
    }

    fun showProgress() {
        getBaseActivity()?.showProgress()
    }

    fun dismissProgress() {
        LogUtils.error("fragment dismissProgress:" + getBaseActivity() == null)
        getBaseActivity()?.dismissProgress()
    }

    open fun onBackPressed(): Boolean {
        return true
    }


    fun startParentActivity(clazz: Class<out Fragment>, bundle: Bundle? = null) {
        val builder = IntentBuilder.Builder()
        bundle?.let {
            builder.putExtras(it)
        }
        builder.startParentActivity(activity, clazz)
    }


    fun <K, V : Any> startParentActivity(clazz: Class<out Fragment>, vararg params: Pair<K, V>?) {
        IntentBuilder.Builder().also {
            params?.forEach { param->
                it.putExtra(param?.first.toString(), param?.second?.toJson())
            }
        }.startParentActivity(activity, clazz)
    }

    fun startActivity(clazz: Class<out Activity>) {
        IntentBuilder.Builder().setClass(requireContext(), clazz).startActivity()
    }

}

